package com.gcloud.mesh.dcs.chain.huawei;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.strategy.huawei.RegionType;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.sms.v3.SmsClient;
import com.huaweicloud.sdk.sms.v3.model.*;
import com.huaweicloud.sdk.sms.v3.region.SmsRegion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CreateTask_3 extends AbstractHuaweiMigrationStep{
    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {

        JSONObject jsonObject = JSONObject.parseObject(attach);
        HuaweiMigrationParam huaweiMigrationParam = JSONObject.toJavaObject(jsonObject,HuaweiMigrationParam.class);
        String sourceServerId = jsonObject.getString("sourceServerId");
        List<TargetDisks> disks = JSONArray.parseArray(jsonObject.getString("targetDisks"), TargetDisks.class);
        String osType = jsonObject.getString("osType");
        String taskId = createTask(huaweiMigrationParam.getMyJobId(), huaweiMigrationParam.getAccessKey(), huaweiMigrationParam.getSecretKey(), huaweiMigrationParam.getVmName(), huaweiMigrationParam.getDestRegionId(), disks, sourceServerId, osType);
        jsonObject.put("taskId",taskId);
        filterChain.doExec(schedulerJobId,jsonObject.toString(),filterChain,stepChain);
    }

    @Override
    public String chainName(String attach) {
        return "创建迁移任务";
    }

    @Override
    public int getOrder() {
        return 3;
    }

    public String createTask(String jobId, String ak, String sk, String name, String regionId, List<TargetDisks> disk, String sourceServerId, String osType) {
        if(StringUtils.isBlank(ak)) {
            ak = "8QVISVT4XJHUNMIEPZBQ";
        }
        if(StringUtils.isBlank(sk)) {
            sk = "GingsSlHInSkQ3x47jMSEjFT0uumSJgplZs926Cw";
        }
        if(StringUtils.isBlank(regionId)) {
            regionId = "cn-north-1";
        }
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        config.withIgnoreSSLVerification(true);
        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        SmsClient client = SmsClient.newBuilder()
                .withCredential(auth)
                .withHttpConfig(config)
                .withRegion(SmsRegion.valueOf("ap-southeast-1"))
                .build();
        CreateTaskRequest request = new CreateTaskRequest();
        PostTask body = new PostTask();
        List<VolumeGroups> listTargetServerVolumeGroups = new ArrayList<>();
        // List<PhysicalVolumes> listDisksPhysicalVolumes = new ArrayList<>();
        // String sourceServerId = getSourceServerId(ak, sk, name);
        log.debug("源服务器迁移id是"+sourceServerId);
        // System.out.println("源id:"+sourceServerId);
        List<TargetDisks> listTargetServerDisks = disk;
//        		new ArrayList<>();
//        listTargetServerDisks.add(
//            new TargetDisks()
//                .withName("test")
//                .withPhysicalVolumes(listDisksPhysicalVolumes)
//                .withSize(42948624384L)
//                .withUsedSize(2831396864L)
//        );
        List<BtrfsFileSystem> listTargetServerBtrfsList = new ArrayList<>();
        TargetServerByTask targetServerbody = new TargetServerByTask();
        targetServerbody.withName(name);
        targetServerbody.withBtrfsList(listTargetServerBtrfsList)
                .withDisks(listTargetServerDisks)
                .withVolumeGroups(listTargetServerVolumeGroups);
        SourceServerByTask sourceServerbody = new SourceServerByTask();
        sourceServerbody.withId(sourceServerId);
        body.withUsePublicIp(true);
        body.withVmTemplateId(RegionType.getRegionType(regionId).getTemplateId());
        body.withProjectId(RegionType.getRegionType(regionId).getProjectId());
        body.withProjectName(regionId);
        body.withRegionId(regionId);
        body.withRegionName(RegionType.getRegionType(regionId).getRegionName());
        body.withTargetServer(targetServerbody);
        body.withSourceServer(sourceServerbody);
        body.withOsType(osType);
        body.withType("WINDOWS".equals(osType)?PostTask.TypeEnum.fromValue("MIGRATE_BLOCK"):PostTask.TypeEnum.fromValue("MIGRATE_FILE"));
        body.withName("mesh_test");
        request.withBody(body);
        String taskId = null;
        try {
            CreateTaskResponse response = client.createTask(request);
            taskId = response.getId();
        } catch (ConnectionException e) {
            log.error("迁移创建任务连接失败："+ e);
        } catch (RequestTimeoutException e) {
            log.error("迁移创建任务超时："+ e);
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            log.error("迁移创建任务异常："+ e.getErrorMsg());
        }
        return taskId;
    }
}
